package com.app.zhuozhuo

import android.util.Log
import java.io.BufferedInputStream
import java.io.File
import java.io.File.separatorChar
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL


/**
 *  Create by zhouwd on 2020-01-10
 *  Describe:
 */

private val TAG = NetworkFactory::class.java.simpleName

class NetworkFactory(private val url: String, private val savePath: String) : Runnable {

    override fun run() {

        var bis: BufferedInputStream ?= null

        try {
            // 统一资源
            val url = URL(url)
            // 连接类的父类，抽象类
            val urlConnection = url.openConnection()
            // http的连接类
            val httpURLConnection = urlConnection as HttpURLConnection
            // 设定请求的方法，默认是GET
            httpURLConnection.requestMethod = "POST"
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8")
            // 打开到此 URL 引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect()

            bis = BufferedInputStream(httpURLConnection.inputStream)

            bis.use {fis ->
                val file = File(savePath)

                if (!file.exists()) {

                    val parent = file.parentFile

                    if (!parent.exists()) {
                        parent.mkdirs()
                    }

                }

                FileOutputStream(file).use { fos ->
                    //创建缓冲区输入流
                    val bis = fis.buffered()
                    //创建缓冲区输出流
                    val bos = fos.buffered()
                    //复制到输出流
                    bis.copyTo(bos)

                    Log.i(TAG, "复制完成")

                }
            }
        } catch (e: MalformedURLException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } catch (e: IOException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } finally {
            if (bis != null) {
                try {
                    bis.close()
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }
        }
    }
}